package com.example.demo.common;

import com.example.demo.constant.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器
@Component
public class LoginIntercepter implements HandlerInterceptor {
    //拦截器前置处理方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果默认参数是true，如果没有session，会新建一个session返回
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constants.SESSION_USER_INFO) != null) {
            return true;
        }
        response.setStatus(401);//401是http的状态码
        //返回false，说明拦截成功
        return false;
    }
}
